package com.turtle.learning.auth.service;

import com.turtle.learning.auth.dto.LoginUserInfo;
import com.turtle.learning.auth.utils.TokenOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录验证
 *
 * @author turtle
 * date: 2020-05-07
 */
@Component
@Slf4j
public class LoginService {


    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenOperator tokenOperator;

    /**
     * 登录验证
     *
     * @param username 登录账号
     * @param password 登录密码
     * @return 验证结果
     */
    public String login(String username, String password) {
        Authentication authentication = null;

        try {
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }

        LoginUserInfo loginUserInfo = (LoginUserInfo) authentication.getPrincipal();

        return tokenOperator.generateToken(loginUserInfo);

    }
}
